﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;
using Util.Extension;
using AntUnion.FrameWork.Util;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class PowerController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public PowerController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }
        #region 权限列表
        public IActionResult Index(int menuid)
        {
            ViewBag.menuid = menuid;
            return View();
        }

        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int menuid)
        {
            ListResult res = new ListResult();
            try
            {
                var data = await _context.TbPowers.Where(k => k.MenuId == menuid).OrderBy(k => k.Sort).ToListAsync();
                res.Code = 0;
                res.Count = _context.TbPowers.Where(k => k.MenuId == menuid).Count();
                res.Data = data;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加权限
        public IActionResult Create(int menuid)
        {
            TbPower TbPower = new TbPower
            {
                MenuId = menuid
            };
            return View(TbPower);
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(TbPower model)
        {
            Result res = new Result();
            try
            {
                if (!TbPowerExists(model.Names, model.MenuId))
                {
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTimeUtil.Now;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "权限名称已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑权限信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            TbPower TbPower = await _context.TbPowers.FindAsync(id);
            if (TbPower == null)
            {
                return NotFound();
            }
            return View(TbPower);
        }
        /// <summary>
        /// 编辑权限信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(TbPower item)
        {
            Result res = new Result();
            try
            {
                if (!TbPowerExists(item.Names, item.MenuId, item.Id))
                {
                    TbPower model = await _context.TbPowers.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.Names = item.Names;
                        model.MenuId = item.MenuId;
                        model.Controller = item.Controller;
                        model.Action = item.Action;
                        model.Sort = item.Sort;
                        model.Remark = item.Remark;
                        
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "权限不存在";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "权限名称已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除权限
        /// <summary>
        /// 删除单个权限
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                TbPower TbPower = await _context.TbPowers.FindAsync(id);
                
                _context.TbPowers.Remove(TbPower);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的权限ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbPower> userList = await _context.TbPowers.Where(k => list.Contains(k.Id)).ToListAsync();
                foreach (TbPower model in userList)
                {
                    _context.TbPowers.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">权限名称称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbPowerExists(string Name, int menuid, int id = 0)
        {
            if (id == 0)
                return _context.TbPowers.Any(e => e.Names == Name && e.MenuId == menuid);
            else
                return _context.TbPowers.Any(e => e.Id != id && e.MenuId == menuid && e.Names == Name);
        }
        #endregion
    }
}